<?php
namespace app\common\model\food;

use Endroid\QrCode\QrCode as CodeMode;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 线下发券模型
 */
class CouponOffline extends BaseModel
{
    // 定义表名
    protected $name = 'food_coupon_offline';
    // 定义主键
    protected $pk = 'coupon_offline_id';
    // 追加字段
    protected $append = ['qrcode'];

    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }
    /**
     * 关联优惠券表
     */
    public function coupon()
    {
        return $this->belongsTo('app\\common\\model\\food\\Coupon','coupon_id');
    }
    
    /**
     * 普通二维码参数
     */
    public function getQrcodeAttr($value,$data)
    {
        return base_url() . 'food/' . $data['applet_id'] . '/coupon-' . $data['coupon_offline_id'];
    }
    
    /**
     * 到期时间
     */
    public function getExpireTimeAttr($value)
    {
        $time = $value - time();
        if($time > 86400){ 
            $text = round($time / 86400) . '天';
        }elseif($time > 3600){
            $text = round($time / 3600) . '小时';
        }elseif($time > 60){
            $text = round($time / 60) . '分钟';
        }else{
            $text = '已过期';
        }
        return ['text' => $text, 'value' => $value];
    }
    
    /**
     * 状态
     */
    public function getStatusAttr($value)
    {
        $status = [10 => '待领取', 20 => '已领取'];
        return ['text' => $status[$value], 'value' => $value];
    }
    
    /**
     * 获取列表
     */
    public function getList()
    {
        //提前3分钟删除即将到期未领取优惠券
        $this->where('status',10)->where('expire_time','<',time()-180)->delete();
        return $this->with(['coupon','shop'])
            ->order('coupon_offline_id','desc')
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }
    
    /**
     * 添加
     */
    public function add(array $data)
    {
        $expire_time = time() + (int)$data['day']*60*60*24;
        //组成用户批量记录
        $coupon = array();
        for($n=0;$n<$data['count'];$n++){
            array_push($coupon,[
                'coupon_id' => $data['coupon_id'],
                'expire_time' => $expire_time,
                'shop_id' => $data['shop_id'],
                'applet_id' => self::$applet_id
            ]);
        }
        return $this->saveAll($coupon);
    }
    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();
    }
    
    /**
     * 核销优惠券
     */
    public function writeOff($user_id)
    {
        if($this->status['value'] == 20){
            $this->error = '该优惠券已被领取';
            return false;
        }
        $coupon = $this->coupon;
        if($coupon['type']['value'] == 10 and $coupon['mode'] == 1){
           //现金立减券线下领取增加用户余额内
    		$user = User::get($user_id);
    		$user->money = ['inc', (int)$coupon['values']['money']];//余额
    		if(!$user->save()){
    		    $this->error = '赠送余额过程失败';
                return false;
    		}
    		//增加赠送记录
    		$model = new Record;
            $model->save([
                'mode' => 40,
                'order_no' => order_no(),
                'money' => (int)$coupon['values']['money'],
                'remark' => '线下推广赠送',
                'user_id' => $user_id,
                'shop_id' => $this->shop_id,
                'applet_id' => self::$applet_id
            ]);
        }else{
            $model = new CouponUser;
            $data[0] = $coupon;
            if(!$model->add($data,$user_id)){
                $this->error = '领取过程失败';
                return false;
            }
        }
        return $this->save(['status' => 20]) !== false;
    }
    
    /**
     * 添加
     */
    public function qrcode()
    {
        if(!file_exists('./temp')){
            mkdir('./temp',0777,true);
        }
        $file_name = 'coupon-' . $this->coupon_offline_id;
        //生成二维码
        $writer = new PngWriter();
        $qrCode = CodeMode::create(base_url() . 'food/' . $this->applet_id . '/' . $file_name)
            ->setSize(500);
        $result = $writer->write($qrCode);
        $result->saveToFile('./temp/' . $file_name . '.png');
        return '/temp/' . $file_name . '.png';
    }
}